package com.chengjj.kings.config.web;

import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.data.redis.connection.convert.StringToDataTypeConverter;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * @Author: 成俊杰
 * @CreateDate: 2019/3/8
 * @Version: 1.0
 * @Description: 时间字符串转换器配置
 */
@Configuration
public class String2DateConfig {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    /**
     * 默认时间转换器
     *  被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行，
     *  并且只会被服务器调用一次，类似于Serclet的inti()方法。
     *  被@PostConstruct修饰的方法会在构造函数之后，init()方法之前运行
     */
    @PostConstruct
    public void addConversionConfig() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
        if ((initializer != null ? initializer.getConversionService() : null) != null) {
            GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
            genericConversionService.addConverter(new StringToDateConverter());
        }
    }

    public class StringToDateConverter implements Converter<String, Date> {

        @Override
        public Date convert(String s) throws IllegalArgumentException {
            return DateUtil.parse(s);
        }
    }
}
